package com.hh.erp.util;

import com.hh.erp.util.http.DiscoveryException;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

public class RedisUtil {

    /**
     * 模拟redis 缓存
     */
    private static Boolean redisStatus = false;

    /**
     * 未设置的情况下默认30分钟
     */
    private static Integer minutes = 30;

    private static Map<String, RedisModel> maps = new HashMap<>();


    public static void add(String key, String value) {
        if (StringUtil.IsSpace(key)) {
            throw new DiscoveryException("key不能为空!");
        }
        if (value == null) {
            throw new DiscoveryException("value不能为空!");
        }
        if (maps.containsKey(key)) {
            throw new DiscoveryException("key值已存在!");
        }
        RedisModel redisDoc = new RedisModel(key, value, LocalDateTime.now(), LocalDateTime.now().plusMinutes(minutes));
        maps.put(key, redisDoc);
    }

    public static boolean containsKey(String key) {
        if (StringUtil.IsSpace(key)) {
            throw new DiscoveryException("key不能为空!");
        }
        if (!maps.containsKey(key)) {
            return false;
        }
        RedisModel redisDoc = maps.get(key);
        if (!redisDoc.getStatus()) {
            return false;
        }
        return true;
    }

    public static void remove(String key) {
        if (StringUtil.IsSpace(key)) {
            throw new DiscoveryException("key不能为空!");
        }
        maps.remove(key);
    }

    public static void edit(String key, String value) {
        if (StringUtil.IsSpace(key)) {
            throw new DiscoveryException("key不能为空!");
        }
        if (value == null) {
            throw new DiscoveryException("value不能为空!");
        }
        if (!maps.containsKey(key)) {
            throw new DiscoveryException("key未存在!");
        }
        RedisModel redisDoc = new RedisModel(key, value, LocalDateTime.now(), LocalDateTime.now().plusMinutes(minutes));
        maps.put(key, redisDoc); // map 会自动覆盖
    }

    public static String getValue(String key) {
        RedisModel redisDoc = maps.get(key);
        if (redisDoc != null && redisDoc.getStatus().compareTo(false) == 0) {
            return null;
        }
        return redisDoc.getValue();
    }
}

